﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Threading.Tasks;

namespace FastData
{
    public class SelectQuery<T> : IQueryable<T>, IQueryable, IEnumerable<T>, IEnumerable, IOrderedQueryable<T>, IOrderedQueryable
    {
        private IQueryProvider _provider;
        private Expression _expression;

        internal SelectQuery(DataAccess data)
        {
            _provider = new SelectQueryProvider<T>(data);
            _expression = Expression.Constant(this);
        }

        internal SelectQuery(IQueryProvider provider, Expression expression)
        {
            _provider = provider;
            _expression = expression;
        }

        public Expression Expression
        {
            get { return _expression; }
        }

        public Type ElementType
        {
            get { return typeof(T); }
        }

        public IQueryProvider Provider
        {
            get { return _provider; }
        }

        public IEnumerator<T> GetEnumerator()
        {
            return ((IEnumerable<T>)_provider.Execute(_expression)).GetEnumerator();
        }

        IEnumerator IEnumerable.GetEnumerator()
        {
            return ((IEnumerable)_provider.Execute(_expression)).GetEnumerator();
        }

        internal async Task<IEnumerable<T>> ExecuteAsync()
        {
            return await ((SelectQueryProvider<T>)_provider).ExecuteAsync(_expression);
        }

        public override string ToString()
        {
            return _expression.ToString();
        }
    }
}
